package com.stone.starter.core.exception.handler;

import com.stone.starter.core.constant.BaseConstants;
import com.stone.starter.core.exception.CommonException;
import com.stone.starter.core.exception.ExceptionResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 程序异常处理器
 *
 * @author jiangzhou.bo@hand-china.com 2018/06/14 11:19
 */
// @ControllerAdvice
public class BaseExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseExceptionHandler.class);

    @Value("${spring.profiles.active:" + BaseConstants.DEFAULT_ENV + "}")
    private String env;


    @ExceptionHandler(CommonException.class)
    public ResponseEntity<ExceptionResponse> process(CommonException exception) {
        LOGGER.info("exception info {}", exception.getTrace());
        ExceptionResponse er = new ExceptionResponse();
        setDevException(er, exception);
        return new ResponseEntity<>(er, HttpStatus.OK);
    }

    private void setDevException(ExceptionResponse er, Exception ex) {
        if (BaseConstants.DEFAULT_ENV.equals(env)) {
            er.setException(ex.getMessage());
            er.setTrace(ex.getStackTrace());

            Throwable cause = ex.getCause();
            if (cause != null) {
                er.setThrowable(cause.getMessage(), cause.getStackTrace());
            }
        }
    }

}